package gui;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.prefs.Preferences;

import javax.swing.ImageIcon;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JProgressBar;

import Aplicacion.Variables_globales;

public class SplashScreen implements Runnable {
//	private final BufferedImage[] imagenes = new BufferedImage[43];
//	private final Database db = new Database();
	private JFrame frame;
	private JProgressBar progressBar;
	private JLabel label;
	private Thread parseImages;

	public SplashScreen() {
		this.initialize();
		frame.setVisible(true);
		
//		Variables_globales.PARTIDA_ID = db.getIniPartida();
//		Variables_globales.PARTIDA_ID = 1;
		this.checkDatabase();
		
		Variables_globales.SHARING.start();
		
//		Variables_globales.LISTA_JUGADORES.add(new Jugadores(1, "Jugador 1", Color.RED));
//		Variables_globales.LISTA_JUGADORES.add(new Jugadores(2, "Jugador 2", Color.BLUE));
		
//		for (Jugadores j: Variables_globales.LISTA_JUGADORES) {
//			db.add_jugador_a_la_partida(j);
//		}
//		
//		Variables_globales.JUGADOR_ACTUAL = (int)(Math.random()*Variables_globales.LISTA_JUGADORES.size());
//		Variables_globales.JUGADOR_ACTUAL = 1;
		
		parseImages = new Thread(this);
		parseImages.start();
	}

	private void initialize() {
		frame = new JFrame();
		frame.setUndecorated(true);
		frame.setResizable(false);
		frame.setSize(870, 537);
		frame.setLocationRelativeTo(null);
		frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
		frame.getContentPane().setLayout(null);
		
		progressBar = new JProgressBar();
		progressBar.setMaximum(43);
		progressBar.setBounds(17, 0, 831, 28);
		frame.getContentPane().add(progressBar);
		
		label = new JLabel("");
		label.setBounds(0, 0, 870, 537);
		label.setIcon(new ImageIcon(SplashScreen.class.getResource("/Imagenes/SplashScreen.png")));
		frame.getContentPane().add(label);
	}

	@Override
	public void run() {
//		Image tmp = null;
//		String tmpName;
//		BufferedImage bimage;
		
		float tInicio	= 0f;
		float tFin		= 0f;
		
		for (int i=0;i<43;i++) {
//		for (int i=0;i<imagenes.length;i++) {
			tInicio = System.currentTimeMillis();
//			tmpName = String.format("/Imagenes/mapa/paisesSueltos/PaisSuelto_%02d.png", i);
			
//			System.out.println(tmpName);
			
//			tmp = Toolkit.getDefaultToolkit().createImage(SplashScreen.class.getClass().getResource(tmpName));
//			bimage = getBufferedImageFromImage(tmp);
			
			progressBar.setValue(progressBar.getValue()+1);
			
			tFin = System.currentTimeMillis();
			if ((tFin-tInicio) < 30) {
				try {
					Thread.sleep((long) (30-(tFin-tInicio)));
				} catch (InterruptedException e) {}
			}
			
//			label.setIcon(new ImageIcon(bimage));
//			imagenes[i] = bimage;
//			tmp = null;
		}
		
//		Variables_globales.IMAGENES = imagenes;
		frame.dispose();
		new Ventana();
	}
	
//	private BufferedImage getBufferedImageFromImage(Image img) {
//        img = new ImageIcon(img).getImage(); 
//        BufferedImage bufferedImage = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
//        Graphics g = bufferedImage.createGraphics();
//        g.drawImage(img, 0, 0, null);
//        g.dispose();
//        
//        return bufferedImage; 
//    } 
	
	
	
// ### MARK: Base de Datos
	
	private void checkDatabase () {
		Preferences pref = Preferences.userRoot().node("com.karallo.riskLogic");
		pref.put("Path", "null");
		if (pref.get("Path", "null").equals("null")) {
		    JFileChooser chooser = new JFileChooser();
		    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
		    int returnVal = chooser.showOpenDialog(frame);
		    if(returnVal == JFileChooser.APPROVE_OPTION) {
		       System.out.println("You chose to open this file: " + chooser.getCurrentDirectory() + "/" + chooser.getSelectedFile().getName() + "/Risk3.sqlite");
		       
		       try {
		    	   copyFiles(
		    			   new File(this.getClass().getResource("./../data/Risk3.sqlite").toString()),
		    			   new File(pref.get("Path", "null"))
		    	   );
		       } catch (IOException e) {
		    	   System.err.println("Error Creando Base de Datos: "+e.getMessage());
		       }
		       
		       pref.put("Path", chooser.getCurrentDirectory() + "/" + chooser.getSelectedFile().getName() + "/Risk3.sqlite");
		    }
		}
	}
	
	public static void copyFiles(File sourceLocation , File targetLocation) throws IOException {
	        if (sourceLocation.isDirectory()) {
	        	System.out.println("entrando...");
	            if (!targetLocation.exists()) {
	            	System.out.println("creando...");
	                targetLocation.mkdir();
	            }
	            File[] files = sourceLocation.listFiles();
	            for(File file:files){
	                InputStream in = new FileInputStream(file);
	                OutputStream out = new FileOutputStream(targetLocation+"/"+file.getName()+"Risk3.sqlite");
	
	            // Copy the bits from input stream to output stream
	            byte[] buf = new byte[1024];
	            int len;
	            while ((len = in.read(buf)) > 0) {
	                out.write(buf, 0, len);
	            }
	            in.close();
	            out.close();
	        }            
	    }
	}
}
